<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<c:set var="ctx" value="${pageContext.request.contextPath}"/>
<c:set var="qiniu" value="http://upload.qiniu.com/"/>
<html>
<head>
    <title>首页</title>
</head>
<body>
<h1>Welcome</h1>
<div>
    <form id="uploadForm" method="post" action="http://upload.qiniu.com/" enctype="multipart/form-data">
        <input id="key" name="key" type="hidden"/>
        <input id="token" name="token" type="hidden"/>
        <input name="file" type="file"/>
    </form>
    <div>
        <button id="btn_upload" class="btn btn-default">上传</button>
    </div>
</div>
<script type="text/javascript">
    function generateUUID() {
        var d = new Date().getTime();
        var uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
            var r = (d + Math.random()*16)%16 | 0;
            d = Math.floor(d/16);
            return (c=='x' ? r : (r&0x3|0x8)).toString(16);
        });
        return uuid;
    };

    $(document).ready(function () {
        var options = {
            //图片上传完后的操作
            success: function (data) {
                alert(data.key);
            }
        }

        $('#uploadForm').submit(function () {
            $(this).ajaxSubmit(options);
            return false;
        });

        $('#btn_upload').click(function () {
            //图片上传之前，先生成uuid作为图片的key，同时同步的请求获取七牛的token
            $('#key').val(generateUUID().replace(/-/g, ''));
            $.ajax({
                url: 'api/qiniu/tokenSimple',
                async:false,
                success: function(json){
                    $('#token').val(json.data.token);
            }});
            $('#uploadForm').submit();
        });
    });
</script>
</body>
</html>
